package com.colin.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.URL;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WxHttpClient {
    private static final Logger logger = LoggerFactory.getLogger(WxHttpClient.class);
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final int DEFAULT_TIME_OUT = 60 * 1000;

    public static String doHttpsGet(String requestUrl, Map<String, String> headers) throws Exception{
        return doHttpsGet(requestUrl, headers, DEFAULT_CHARSET, DEFAULT_TIME_OUT);
    }

    public static String doHttpsGet(String requestUrl, Map<String, String> headers,String charset, int timeout) {
        String result = "";
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setConnectTimeout(timeout);
            httpUrlConn.setReadTimeout(timeout);

            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("GET");

            //设置请求头
            if(headers != null && headers.size() > 0){
                for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
                    httpUrlConn.setRequestProperty(headerEntry.getKey(), headerEntry.getValue());
                }
            }

            int code = httpUrlConn.getResponseCode();
            logger.info("http response code:" + code);

            InputStream inputStream = null;
            if(code == 200){
                // 将返回的输入流转换成字符串
                inputStream = httpUrlConn.getInputStream();
            }else{
                inputStream = httpUrlConn.getErrorStream();
            }

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            result = buffer.toString();
        } catch (ConnectException ce) {
            logger.error("https request connection timed out", ce);
        } catch (Exception e) {
            logger.error("https request error", e);
        }
        return result;
    }
}
